TEAM_OB = class("TEAM_OB")
TEAM_OB:inherit(F_COMN_DBASE)

------------------------
--队伍
--[[
    id: id,
    captain: user_id 队长
    fighting: bool 是否在战斗中
    users : {
        _user_id 玩家id : begin_time 玩家加入时间,
    }
]]
------------------------

function TEAM_OB:clear()
    self:delete_temp("id")
    self:delete_temp("users")
    self:delete_temp("captain")
    self:delete_temp("fighting")
end

---! 获取Id
function TEAM_OB:get_id()
    return self:get_temp("id") or 0
end

function TEAM_OB:set_id(id)
    return self:set_temp("id", id)
end

function TEAM_OB:get_fighting()
    return self:get_temp("fighting")
end

function TEAM_OB:set_fighting(fighting)
    return self:set_temp("fighting", fighting)
end

---! 获取队长
function TEAM_OB:get_captain()
    return self:get_temp("captain") or 0
end

function TEAM_OB:set_captain(captain)
    return self:set_temp("captain", captain)
end

---! 获取所有users {id=time,...}
function TEAM_OB:get_users()
    return self:get_temp("users") or {}
end

---! 增加多人 users: {ids}
function TEAM_OB:set_users(users)
    local _users = self:get_users() --原来队伍成员
    _users = _users or {}
    for _, _user_id in pairs(users) do
        _users[_user_id] = os.time()
    end
    self:set_temp("users", _users)
    return true
end

---! 第一个加入的
function TEAM_OB:get_first_join()
    local _users = self:get_users()
    local min_time = 0
    local min_id = 0
    for user_id, btime in pairs(_users) do
        if min_time == 0  or btime < min_time then
            min_time = btime
            min_id = user_id
        end
    end
    return min_id
end

---! 刪除
function TEAM_OB:del_user(user_id)
    local users = self:get_users()
    for _user_id, _ in pairs(users) do
        if _user_id == user_id then
            users[_user_id] = nil
            self:set_temp("users", users)
            return
        end
    end
end

---! 获取所有users
function TEAM_OB:get_user_ids()
    local ids = {}
    for _user_id, _ in pairs(self:get_users()) do
        table.insert(ids,_user_id)
    end
    return ids
end

---! 获取所有有效user
function TEAM_OB:get_user_obs()
    local user_obs = {}
    for user_id, _ in pairs(self:get_users()) do
        local user_ob = USER_D:find_user(user_id)
        if user_ob then
            table.insert(user_obs, user_ob)
        end
    end
    return user_obs
end

---! 获取一个用户
function TEAM_OB:get_user(user_id)
    for _user_id, _begin_time in pairs(self:get_users()) do
        if _user_id == user_id then
            local u = {}
            u[user_id] = _begin_time
            return u
        end
    end
    return nil
end

---! 获取加入时间
function TEAM_OB:get_begin_time(user_id)
    local user = self:get_user(user_id)
    if user then
        return user[user_id]
    end
    return os.time()
end

---! 获取人数
function TEAM_OB:get_user_num()
    local users = self:get_users()
    return table.size(users)
end

function TEAM_OB:__tostring()
    return string.format("TEAM_OB [%s:%d:%d]", self:get_id(),self:get_captain(),self:get_user_num())
end
